#include <string.h>
#include<stdlib.h>
#include <jni.h>
#include <math.h>

void Java_com_picturetransform_binarization_PictureBinarization_transform(JNIEnv* env, jobject javaThis, jintArray bitmap, jint width, jint height) {

	int i, j, k, l;
	int sec = 0;
	

	int numberOfSectorsWidth = width/16;
	int numberOfSectorsHeight = height/12;

	jint* destBitmap = (*env)->GetIntArrayElements(env, bitmap, NULL);
	
	int sectorHeight = (int)height / numberOfSectorsWidth;
	int sectorWidth = (int) width / numberOfSectorsHeight;
	
	double threshold[numberOfSectorsWidth][numberOfSectorsHeight];
	int sectorSize = sectorHeight * sectorWidth;

	for (k = 0; k < numberOfSectorsWidth; k++) {
		for (l = 0; l < numberOfSectorsHeight; l++) {
			
			double sum = 0;
			for (i = 0; i < sectorWidth-1; i++) {
	
				for (j = 0; j < sectorHeight-1; j++) {
					int pixelIntValue = destBitmap[(l * sectorWidth + i)*height + k* sectorHeight + j];
	
					int r = (pixelIntValue >> 16) & 0xFF;
					int g = (pixelIntValue >> 8) & 0xFF;
					int b = (pixelIntValue >> 0) & 0xFF;
					sum += (r + g + b) / 3;
				}
			}
			
			double average = sum / sectorSize;
			
			sum = 0;
			for (i = 0; i < sectorWidth-1; i++) {
	
				for (j = 0; j < sectorHeight-1; j++) {
					int pixelIntValue = destBitmap[(l * sectorWidth + i)*height + k* sectorHeight + j];
	
					int r = (pixelIntValue >> 16) & 0xFF;
					int g = (pixelIntValue >> 8) & 0xFF;
					int b = (pixelIntValue >> 0) & 0xFF;
	
					sum += pow(((r + g + b) / 3) - average, 2);
	
				}
			}
			
			double variance = sqrt(sum / sectorSize);
			
			int z = 0.34;
			int R = 128;
			threshold[k][l] = (average * (1 + z * (variance / R - 1)));
		
		}
	}
	for (k = 0; k < numberOfSectorsWidth; k++) {
		for (l = 0; l < numberOfSectorsHeight; l++) {
			for (i = 0; i < sectorWidth; i++) {
				for (j = 0; j < sectorHeight; j++) {
					int pixelIntValue = destBitmap[(l * sectorWidth + i)*height + k* sectorHeight + j];
					int r = (pixelIntValue >> 16) & 0xFF;
					int g = (pixelIntValue >> 8) & 0xFF;
					int b = (pixelIntValue >> 0) & 0xFF;
					int rgbColor = (r + g + b) / 3;

				
					if (rgbColor >= threshold[k][l])
						destBitmap[(l * sectorWidth + i)*height + k* sectorHeight + j] =  -1;
					else
						destBitmap[(l * sectorWidth + i)*height + k* sectorHeight + j] = 0;
					}
				}
			}
		}	

     (*env)->ReleaseIntArrayElements(env, bitmap, destBitmap, 0);
}

